import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import './assets/font/iconfont.css'
import store from './store'

import Jquery from 'jquery'
import {SongCon} from './http'

React.Component.prototype.$ = Jquery;
React.Component.prototype.$store = store;

// 播放方法
React.Component.prototype.$play = function(songInfo){
    var audio = this.$('#playTag')[0];
    // console.log($audio)
    audio.src='https://music.163.com/song/media/outer/url?id='+songInfo.id+'.mp3'
    audio.oncanplay = (e)=>{
        audio.play();
    }
    // 获取歌曲信息将其存入store中
    SongCon.getSongDetail(songInfo.id,res=>{
        console.log(res.data.songs[0])
        const action={
            type:'SONG_ADD',
            data:res.data.songs[0]
        }
        this.$store.dispatch(action);
    });
    // 获取歌词并将其保存
    SongCon.getSongLyric(songInfo.id,res=>{
        // 获取歌词
        var lyric = res.data.lrc.lyric.split(/\[.*?\]/);
        // 去掉第一个空字符
        lyric.shift();
        var timeReg = /\[(.*?)\]/g;
        // 获取所有歌词的时间
        var lyricTime= [];
        lyric.forEach(()=>{
            lyricTime.push(timeReg.exec(res.data.lrc.lyric)[1].split(':'));
        });
        // 保存歌词以及歌词时间
        this.$store.dispatch({
            type:'LYRIC_ADD',
            data:lyric
        })
        this.$store.dispatch({
            type:'LYRICTIME_ADD',
            data:lyricTime
        })
    })
    
}
// 格式化时间

React.Component.prototype.$formatTime = function(time){
    var stime = time>=10?parseInt(time):'0'+parseInt(time);
    time = Number(time).toFixed(3);
    time = time>=10?time:'0'+time;
    return {
        time,
        stime
    }
}
// 获取当前正在播放的歌词
React.Component.prototype.$lyric = function(m,s){
    // 判断有没有传递时间
    if(!m){
        var audio = this.$('#playTag')[0];
        // 获取当前播放的时间
        var currentTime = audio.currentTime;
        // 格式化当前播放时间
        // 时分秒
        var s = currentTime%60;
        var m = currentTime/60;
        var {stime:m} = this.$formatTime(m);
        var {time:s} = this.$formatTime(s);

    }
    // 判断当前播放时间歌词
    var ind = 0;
    this.$store.getState().lyricTime.forEach((item,index)=>{
        if(Number(m)>=Number(item[0])){
            if(Number(m)==Number(item[0])){
                if(s>=item[1]){
                    ind = index;
                }
            }else{
                ind = index;
            }
        }
    })
    // console.log(this.$store.getState().lyric[ind])
    
    // console.log(s,m,this.$store.getState().lyric[ind],ind)
    return this.$store.getState().lyric[ind];
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
